<template>
  <div>
    <el-calendar :range="range" v-model="today">
      <template slot="dateCell" slot-scope="{ date, data }">
        <el-button type="primary"  plain @click="add(data.day)">{{ data.day }} </el-button>
        <plan-list :plans="getContent(data.day)" @onPlanClick="onPlanClick" @onDelete="onDelete" @onFinish="onFinish"></plan-list>
      </template>
    </el-calendar>
    <el-dialog
      title="新增日计划"
      :visible.sync="addDialogVisible"
      width="30%"
      >
      <plan-add-form :day="selectedDay" @addDialogClose="addDialogClose"></plan-add-form>
    </el-dialog>
    <el-dialog
      title="计划详情"
      :visible.sync="detailDialogVisible"
      width="30%">
      <plan-detail :plan="selectedPlan" @detailDialogClose="detailDialogClose"></plan-detail>
    </el-dialog>
    <el-dialog title="警告"
      :visible="deleteDialogVisible"
      width="15%">
      <span>确定删除这条计划？</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelDelete">取 消</el-button>
        <el-button type="primary" @click="deletePlan">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import plan_list from "../components/plan_list";
import plan_add_form from "./plan/add";
import plan_detail from "./plan/detail";

var today = new Date();
var weekIndex = today.getDay();
var dayIndex = today.getDate();
var lastMonday = new Date(today.setDate(dayIndex - 7 - weekIndex + 1));
var nextSunday;
today = new Date();
if (weekIndex == 0){ // 星期天
  nextSunday = new Date(today.setDate(dayIndex + 7));
}else{
  nextSunday = new Date(today.setDate(dayIndex + 7 +  7 - weekIndex));
}

export default {
  name: "Calandar",
  components: { "plan-list": plan_list,"plan-add-form":plan_add_form, "plan-detail":plan_detail },
  data() {
    return {
      today:new Date(),
      addDialogVisible : false,
      detailDialogVisible:false,
      deleteDialogVisible:false,
      selectedDay:null, // 选择的日期
      selectedPlan:null, // 选择的计划
      rawData: null, // 从后端获取到的未处理的计划列表
      deletePlanId:null, // 暂存需要被删除的计划Id
    };
  },
  computed:{
    range: function(){
      var range = [];
      range.push(lastMonday);
      range.push(nextSunday);
      return range;
    },
    contentData:function(){
      var result = {};
      var contentData = [];
      if (this.rawData){
        this.rawData.forEach(plan =>{
        if (!result[plan.dateStart.substr(0,10)]){
          result[plan.dateStart.substr(0,10)] = {date:plan.dateStart.substr(0,10),content:[{id:plan.id,text:plan.summary,important:true,status:plan.status}]};
        }else{
          result[plan.dateStart.substr(0,10)].content.push({id:plan.id,text:plan.summary,important:true,status:plan.status});
        }
      });

      for (var key in result){
        contentData.push(result[key]);
      }
      
      }
      return contentData;
    }
  },
  methods: {
    click: function (e) {
      console.log(e);
    },
    getContent: function (day) {
      var content = [];
      this.contentData.forEach((data) => {
        if (data.date == day) {
          content = data.content;
        }
      });
      return content;
    },
    add:function(day){
      this.addDialogVisible = true;
      this.selectedDay = day;
    },
    onPlanClick:function(id){
      this.rawData.forEach(plan =>{
        if (plan.id == id){
          this.selectedPlan = plan;
          return false;
        }
      });
      this.detailDialogVisible = true;
    },
    addDialogClose:function(plan){
      if (plan){
        this.rawData.push(plan);
      }
      this.addDialogVisible=false;
    },
    detailDialogClose:function(plan){
      if (plan){
        for (var i = 0; i < this.rawData.lenght; i++){
          if (this.rawData[i].id == plan.id){
            this.rawData[i] = plan;
          }
        }
      }
      this.detailDialogVisible = false;
    },
    onDelete:function(id){
      console.log(id);
      var _this = this;
      this.rawData.forEach(plan =>{
        if (plan.id == id){
          _this.deletePlanId = id;
          _this.deleteDialogVisible = true;
          return false;
        }
      });
    },
    deletePlan:function(){
      var _this = this;
      _this.deleteDialogVisible = false;
      if (this.deletePlanId){
        this.axios.delete("/plan/remove/"+this.deletePlanId).then(function(response){
        
          if (response.data.code == 'OK'){
            _this.$notify({
              title: '提示',
              type: 'success',
              message: '你已成功删除这条计划。'
            });
            window.location.reload(true);
          }else{
            _this.$notify({
              title: '提示',
              type: 'error',
              message: '删除失败，请重试。',
              duration: 0
            });
          }
        });
      }
      this.deleteDialogVisible = false;
      var index = -1;
      for (var i = 0; i < this.rawData.lenght; i++){
        if (this.rawData[i].id == this.deletePlanId){
          index = i;
          break;
        }
      }
      if (index != -1){
        this.rawData.splice(index,1);
      }
      this.deletePlanId = null;
    },
    cancelDelete:function(){
      this.deletePlanId = null;
      this.deleteDialogVisible = false;
    },
    onFinish:function(id){
      var _this = this;
      this.axios.post("/plan/updateStatus/"+ id + "/" + 1).then(function(response){
          if (response.data.code == 'OK'){
            _this.$notify({
              title: '提示',
              type: 'success',
              message: '恭喜你完成一个计划。'
            });
            //window.location.reload(true);
          }else{
            _this.$notify({
              title: '提示',
              type: 'error',
              message: '标记失败，请重试。',
              duration: 0
            });
          }
        });
        for (var i = 0; i < this.rawData.lenght; i++){
          if (this.rawData[i].id == id){
            this.rawData[i].status = 1;
            break;
          }
        }
    }
  },
  created:function(){
    var _this = this;
    var startDay = lastMonday.toLocaleDateString();
    var endDay = nextSunday.toLocaleDateString();
    var url = encodeURI('/plan/get?param=[{"colName":"plan_type","condition":"=","value":"Day"},{"colName":"date_start","condition":">=","value":"'+ startDay +'"},{"colName":"date_end","condition":"<","value":"'+ endDay +'"}]');
    this.axios.get(url).then(
      function(response){
        var data = response.data.data;
        _this.rawData = data;
        
      }
    );
  }
}
</script>

<style>
.el-calendar-day{
    box-sizing: border-box;
    padding: 8px;
    min-height: 180px;
}
</style>